/*
 * ClipboardWindow.java
 *
 * Created on August 9, 2006, 3:32 PM
 */

package org.letva.copie.client.gui;

import java.awt.datatransfer.UnsupportedFlavorException;
import javax.swing.*;
import org.letva.copie.client.Client;
import java.util.LinkedList;
import java.io.*;
import java.net.*;
/**
 *
 * @author  Vuk Nikolic
 */
public class ClientWindow extends javax.swing.JFrame {

    /** Creates new form ClipboardWindow */
    public ClientWindow() {
        initComponents();
        pasteFromDialog.setBounds(this.getX(),this.getY(),400,300);
        connectToSubServerDialog.setBounds(this.getX(),this.getY(),200,180);
        infoDialog.setBounds(this.getX(),this.getY(),300,300);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        pasteFromDialog = new javax.swing.JDialog();
        subServerScrollPane = new javax.swing.JScrollPane();
        subServerList = new javax.swing.JList();
        activeSubServerLabel = new javax.swing.JLabel();
        pasteFromButton = new javax.swing.JButton();
        connectToSubServerDialog = new javax.swing.JDialog();
        subServerSettingsLabel = new javax.swing.JLabel();
        subServerPortTextField = new javax.swing.JTextField();
        connectButton = new javax.swing.JButton();
        portLabel = new javax.swing.JLabel();
        infoDialog = new javax.swing.JDialog();
        infoLabel = new javax.swing.JLabel();
        okButton = new javax.swing.JButton();
        upperPanel = new javax.swing.JPanel();
        textAreaScrollPane = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        openItem = new javax.swing.JMenuItem();
        connectToSubServerItem = new javax.swing.JMenuItem();
        exitItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        cutItem = new javax.swing.JMenuItem();
        copyItem = new javax.swing.JMenuItem();
        pasteItem = new javax.swing.JMenuItem();
        pasteFromItem = new javax.swing.JMenuItem();

        pasteFromDialog.setTitle("Subserver List");
        pasteFromDialog.setAlwaysOnTop(true);
        pasteFromDialog.setModal(true);
        subServerList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        subServerScrollPane.setViewportView(subServerList);

        activeSubServerLabel.setText("Active subservers:");

        pasteFromButton.setText("Paste From");
        pasteFromButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pasteFromButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout pasteFromDialogLayout = new org.jdesktop.layout.GroupLayout(pasteFromDialog.getContentPane());
        pasteFromDialog.getContentPane().setLayout(pasteFromDialogLayout);
        pasteFromDialogLayout.setHorizontalGroup(
            pasteFromDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pasteFromDialogLayout.createSequentialGroup()
                .add(pasteFromDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(pasteFromDialogLayout.createSequentialGroup()
                        .add(84, 84, 84)
                        .add(activeSubServerLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 189, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(pasteFromDialogLayout.createSequentialGroup()
                        .add(73, 73, 73)
                        .add(pasteFromDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(pasteFromButton)
                            .add(subServerScrollPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 264, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(63, Short.MAX_VALUE))
        );
        pasteFromDialogLayout.setVerticalGroup(
            pasteFromDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pasteFromDialogLayout.createSequentialGroup()
                .addContainerGap()
                .add(activeSubServerLabel)
                .add(19, 19, 19)
                .add(subServerScrollPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(23, 23, 23)
                .add(pasteFromButton)
                .addContainerGap(34, Short.MAX_VALUE))
        );
        connectToSubServerDialog.setTitle("Subserver Settings");
        subServerSettingsLabel.setText("SubServer Settings:");

        subServerPortTextField.setText("7770");

        connectButton.setText("Connect");
        connectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectButtonActionPerformed(evt);
            }
        });

        portLabel.setText("Port:");

        org.jdesktop.layout.GroupLayout connectToSubServerDialogLayout = new org.jdesktop.layout.GroupLayout(connectToSubServerDialog.getContentPane());
        connectToSubServerDialog.getContentPane().setLayout(connectToSubServerDialogLayout);
        connectToSubServerDialogLayout.setHorizontalGroup(
            connectToSubServerDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(connectToSubServerDialogLayout.createSequentialGroup()
                .add(24, 24, 24)
                .add(connectToSubServerDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(connectToSubServerDialogLayout.createSequentialGroup()
                        .add(portLabel)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(connectToSubServerDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                            .add(subServerPortTextField)
                            .add(connectToSubServerDialogLayout.createSequentialGroup()
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(connectButton))))
                    .add(subServerSettingsLabel))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        connectToSubServerDialogLayout.setVerticalGroup(
            connectToSubServerDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(connectToSubServerDialogLayout.createSequentialGroup()
                .addContainerGap()
                .add(subServerSettingsLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(connectToSubServerDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(portLabel)
                    .add(subServerPortTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(14, 14, 14)
                .add(connectButton)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        infoDialog.setTitle("Connected!");
        infoLabel.setText("You are connected to subserver.");

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout infoDialogLayout = new org.jdesktop.layout.GroupLayout(infoDialog.getContentPane());
        infoDialog.getContentPane().setLayout(infoDialogLayout);
        infoDialogLayout.setHorizontalGroup(
            infoDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(infoDialogLayout.createSequentialGroup()
                .add(infoDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(infoDialogLayout.createSequentialGroup()
                        .add(21, 21, 21)
                        .add(infoLabel))
                    .add(infoDialogLayout.createSequentialGroup()
                        .add(100, 100, 100)
                        .add(okButton)))
                .addContainerGap(99, Short.MAX_VALUE))
        );
        infoDialogLayout.setVerticalGroup(
            infoDialogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(infoDialogLayout.createSequentialGroup()
                .addContainerGap()
                .add(infoLabel)
                .add(18, 18, 18)
                .add(okButton)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Client");
        setResizable(false);
        textArea.setColumns(20);
        textArea.setFont(new java.awt.Font("Tahoma", 0, 13));
        textArea.setRows(5);
        textAreaScrollPane.setViewportView(textArea);

        org.jdesktop.layout.GroupLayout upperPanelLayout = new org.jdesktop.layout.GroupLayout(upperPanel);
        upperPanel.setLayout(upperPanelLayout);
        upperPanelLayout.setHorizontalGroup(
            upperPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(upperPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(textAreaScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                .addContainerGap())
        );
        upperPanelLayout.setVerticalGroup(
            upperPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(upperPanelLayout.createSequentialGroup()
                .add(textAreaScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 461, Short.MAX_VALUE)
                .addContainerGap())
        );

        fileMenu.setMnemonic('F');
        fileMenu.setText("File");
        openItem.setMnemonic('O');
        openItem.setText("Open");
        openItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openItemActionPerformed(evt);
            }
        });

        fileMenu.add(openItem);

        connectToSubServerItem.setMnemonic('C');
        connectToSubServerItem.setText("Connect To SubServer");
        connectToSubServerItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectToSubServerItemActionPerformed(evt);
            }
        });

        fileMenu.add(connectToSubServerItem);

        exitItem.setMnemonic('E');
        exitItem.setText("Exit");
        exitItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitItemActionPerformed(evt);
            }
        });

        fileMenu.add(exitItem);

        menuBar.add(fileMenu);

        editMenu.setMnemonic('E');
        editMenu.setText("Edit");
        cutItem.setMnemonic('t');
        cutItem.setText("Cut");
        cutItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cutItemActionPerformed(evt);
            }
        });

        editMenu.add(cutItem);

        copyItem.setMnemonic('c');
        copyItem.setText("Copy");
        copyItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                copyItemActionPerformed(evt);
            }
        });

        editMenu.add(copyItem);

        pasteItem.setMnemonic('p');
        pasteItem.setText("Paste");
        pasteItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pasteItemActionPerformed(evt);
            }
        });

        editMenu.add(pasteItem);

        pasteFromItem.setMnemonic('f');
        pasteFromItem.setText("Paste From");
        pasteFromItem.setEnabled(false);
        pasteFromItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pasteFromItemActionPerformed(evt);
            }
        });

        editMenu.add(pasteFromItem);

        menuBar.add(editMenu);

        setJMenuBar(menuBar);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, upperPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(upperPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void openItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openItemActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.addChoosableFileFilter(new FileFilter());
        int result = fc.showOpenDialog(this);
        File file = null;
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;

        switch(result) {
           case JFileChooser.APPROVE_OPTION:
               // znaci rekli smo izaberi taj fajl
                file = fc.getSelectedFile();
                textArea.setText("");
                try {
                    fileReader = new FileReader(file.getPath());
                    bufferedReader = new BufferedReader(fileReader);
                    String line = null;
                    while ((line = bufferedReader.readLine()) != null){
                        textArea.append(line+"\n");
                    }
                } catch (FileNotFoundException e){}
                 catch(IOException e){}


              break;
           case JFileChooser.CANCEL_OPTION: break;
           case JFileChooser.ERROR_OPTION: break;
        }
    }//GEN-LAST:event_openItemActionPerformed

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        infoDialog.setVisible(false);
    }//GEN-LAST:event_okButtonActionPerformed

    private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
        try {
            int port = Integer.parseInt(subServerPortTextField.getText());
            myClipboarder.openConnection("0.0.0.0",port);
            boolean connected = myClipboarder.isConnectedToSubServer();
            if (connected){
                pasteFromItem.setEnabled(true);
                connectToSubServerItem.setEnabled(false);
                connectToSubServerDialog.setVisible(false);
            }
        } catch(SocketException ex){
            this.connectToSubServerDialog.setVisible(false);
            setDialogException("Connection Error",  "Cannot connect to subserver");
        }catch(SocketTimeoutException ex){
            setDialogException("Connection Error", "Subserver timeout!");
        }catch (UnknownHostException e) {
            setDialogException("Unknow Host", "Subserver is not active on this machine.");
        } catch (IOException e) {
            setDialogException("Connection Error", "Problems with input/output operations");
        }  catch (NumberFormatException ex) {
            setDialogException("Port Format Error", "Port must be an integer!");
        }
    }//GEN-LAST:event_connectButtonActionPerformed

    private void connectToSubServerItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectToSubServerItemActionPerformed
        connectToSubServerDialog.setBounds(getX(), getY(), 200, 180);
        connectToSubServerDialog.setVisible(true);
    }//GEN-LAST:event_connectToSubServerItemActionPerformed

    private void pasteFromButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pasteFromButtonActionPerformed
        try {
            myClipboarder.pasteFrom(subServerList.getSelectedIndex());
        } catch (SocketTimeoutException ex) {
            setDialogException("Connection Error", "Subserver timeout!");
        } catch (SocketException ex) {
            setDialogException("Connection Error",  "Connection to subserver is lost!");
        } catch (ClassNotFoundException ex) {
            setDialogException("Internal Error!",  "ClassNotFoundException!!!");
        } catch (IOException ex) {
            setDialogException("Connection Error", "Problems with input/output operations");
        }
        pasteFromDialog.setVisible(false);
    }//GEN-LAST:event_pasteFromButtonActionPerformed

    private void pasteFromItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pasteFromItemActionPerformed
        try{
            LinkedList ll = myClipboarder.getSubServers();

            Object[] objects = myClipboarder.convertSubServersToObjects(ll);
            subServerList.setListData(objects);

            if (ll.size() > 0){
                pasteFromButton.setEnabled(true);
            } else{
                pasteFromButton.setEnabled(false);
            }
            pasteFromDialog.setVisible(true);

         } catch (SocketTimeoutException ex) {
            setDialogException("Connection Error", "Subserver timeout!");
        } catch (SocketException ex) {
            setDialogException("Connection Error", "Connection to subserver is lost!");
        } catch (ClassNotFoundException ex) {
            setDialogException("Internal Error!", "ClassNotFoundException!!!");
        } catch (IOException ex) {
            setDialogException("Connection Error", "Problems with input/output operations");
        }

    }//GEN-LAST:event_pasteFromItemActionPerformed

    private void exitItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitItemActionPerformed

    private void pasteItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pasteItemActionPerformed
        try {
            myClipboarder.paste();
        } catch (UnsupportedFlavorException ex) {
            setDialogException("Ilegal Clipboard content", "The content of the other user's \nclipboard is not plain text.");
        } catch (IOException ex) {
            setDialogException("Connection Error", "Problems with input/output operations");
        }
    }//GEN-LAST:event_pasteItemActionPerformed

    private void copyItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyItemActionPerformed
        myClipboarder.copy(textArea.getSelectedText());
    }//GEN-LAST:event_copyItemActionPerformed

    private void cutItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cutItemActionPerformed
        try{
            myClipboarder.cut(textArea.getSelectedText());
        } catch(Exception e){
            System.out.println(e.toString());
        }
    }//GEN-LAST:event_cutItemActionPerformed

    public void setTextAreaText(String s){
        textArea.setText(s);
    }
    public String getTextAreaText(){
        return textArea.getText();
    }

    public JTextArea getTextArea(){
        return textArea;
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        setLookAndFeel();
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClientWindow().setVisible(true);
            }
        });
    }

    private static void setLookAndFeel(){

    // Install a different look and feel; specifically, the Windows look and feel
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (InstantiationException e) {
        } catch (ClassNotFoundException e) {
        } catch (UnsupportedLookAndFeelException e) {
        } catch (IllegalAccessException e) {
        }
    }

    public void setDialogException(int x, int y, String title, String text){
        pasteFromItem.setEnabled(false);
        connectToSubServerItem.setEnabled(true);
        infoDialog.setTitle(title);
        infoDialog.setBounds(this.getX(), this.getY(), x, y);
        infoLabel.setText(text);
        infoDialog.setVisible(true);
    }

    public void setDialog(String title, String text){
        infoDialog.setTitle(title);
        infoDialog.setBounds(this.getX(), this.getY(), 200, 100);
        infoLabel.setText(text);
        infoDialog.setVisible(true);
    }

    public void setDialogException(String title, String text){
        setDialogException(200, 100, title, text);
    }
    public void setInfoLabel(String s){
        infoLabel.setText(s);
    }

    public void setConnectToSubServerItem(boolean b){
        connectToSubServerItem.setEnabled(b);
    }
    public void setPasteFromItem(boolean b){
        pasteFromItem.setEnabled(b);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel activeSubServerLabel;
    private javax.swing.JButton connectButton;
    private javax.swing.JDialog connectToSubServerDialog;
    private javax.swing.JMenuItem connectToSubServerItem;
    private javax.swing.JMenuItem copyItem;
    private javax.swing.JMenuItem cutItem;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenuItem exitItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JDialog infoDialog;
    private javax.swing.JLabel infoLabel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JButton okButton;
    private javax.swing.JMenuItem openItem;
    private javax.swing.JButton pasteFromButton;
    private javax.swing.JDialog pasteFromDialog;
    private javax.swing.JMenuItem pasteFromItem;
    private javax.swing.JMenuItem pasteItem;
    private javax.swing.JLabel portLabel;
    private javax.swing.JList subServerList;
    private javax.swing.JTextField subServerPortTextField;
    private javax.swing.JScrollPane subServerScrollPane;
    private javax.swing.JLabel subServerSettingsLabel;
    private javax.swing.JTextArea textArea;
    private javax.swing.JScrollPane textAreaScrollPane;
    private javax.swing.JPanel upperPanel;
    // End of variables declaration//GEN-END:variables

    Client myClipboarder = new Client(this);


}
